<template>
	<conf-module-container ref="refConfModuleContainer" class="reflux-config-form">
		<template #Slot-Conf-Module-Header>
			<global-svg-icon
				icon-name="return"
				width="18px"
				height="18px"
				class="header-icon"
				style="margin-right: 8px; cursor: pointer"
				@click="router.go(-1)"
			></global-svg-icon>
			<p class="font-20-bold bread-crumb-title" style="color: #f0f6fc">{{ route.query.id ? '编辑' : '添加' }}</p>
		</template>
		<template #Slot-Conf-Module-Content>
			<a-spin :spinning="pageLoading">
				<div class="form-page">
					<div class="title">
						<global-svg-icon icon-name="config-title-tri" width="3px" height="18px" style="vertical-align: middle"></global-svg-icon>
						<span class="text">{{ route.query.id ? '编辑' : '添加' }}配置</span>
					</div>
					<div class="form-main">
						<div class="form-box">
							<a-form ref="formRef" layout="vertical" :model="formData" :rules="formRules">
								<a-form-item style="padding-bottom: 40px" label-align="left" name="configName" label="配置名称">
									<a-input
										v-model:value.trim="formData.configName"
										style="width: 320px"
										:maxlength="10"
										placeholder="请输入"
										@keypress="handleKeyPress"
									></a-input>
								</a-form-item>
								<a-form-item style="padding-bottom: 40px" label-align="left" name="deviceIds" label="回流设备">
									<a-cascader
										:value="formData.deviceIds"
										multiple
										:get-popup-container="(e: any) => e.parentNode"
										style="width: 320px"
										:options="deviceOptions"
										max-tag-count="responsive"
										:field-names="{ label: 'name', value: 'id', children: 'children' }"
										expand-trigger="hover"
										:style="{ height: 'auto !important' }"
										placeholder="请选择"
										allow-clear
										:show-checked-strategy="'SHOW_CHILD'"
										show-search
										@change="changeDeviceList"
									></a-cascader>
								</a-form-item>

								<a-form-item style="margin-bottom: 32px" label-align="left" name="refluxStrategy" label="回流策略">
									<a-radio-group v-model:value="formData.model" @change="changerefluxStrategyOptions">
										<a-radio :value="0">算法报警回流</a-radio>
										<a-radio :value="1">录像回流</a-radio>
									</a-radio-group>
								</a-form-item>

								<a-form-item
									v-if="formData.model === 0"
									style="margin-bottom: 32px"
									label-align="left"
									name="aiSrvTypeList"
									label="回流算法"
									:rules="[
										{
											required: formData.model === 0,
											message: '请选择回流算法',
											trigger: 'change'
										}
									]"
								>
									<a-select
										v-model:value="formData.aiSrvTypeList"
										placeholder="AI服务"
										max-tag-count="responsive"
										:options="AIServiceList"
										allow-clear
										style="width: 320px"
										:show-search="false"
										show-arrow
										mode="multiple"
										:get-popup-container="
											(triggerNode) => {
												return triggerNode.parentNode;
											}
										"
									>
									</a-select>
								</a-form-item>

								<a-form-item
									v-if="formData.model === 0"
									style="margin-bottom: 32px"
									label-align="left"
									name="alarmTimer"
									:rules="[
										{
											required: formData.model === 0,
											message: '请输入回流时段时段',
											trigger: 'change'
										}
									]"
								>
									<template #label>
										回流时段
										<a-tooltip placement="top" title="按照配置时间录制报警前后时段内的视频数值范围:1~30">
											<i class="iconfont icon-information-line"></i>
										</a-tooltip>
									</template>
									<div class="have-unit-box">
										<a-input-number
											v-model:value="formData.alarmTimer"
											:precision="0"
											:min="1"
											:max="30"
											type="number"
											:style="{
												backgroundColor: 'transparent !important',
												borderColor: 'rgba(240, 246, 252, 0.1) ',
												width: '104px'
											}"
											:maxlength="10"
											placeholder="请输入"
										></a-input-number>
										<span class="unit">秒 </span>
									</div>
								</a-form-item>

								<a-form-item
									v-if="formData.model === 1"
									style="padding-bottom: 40px"
									label-align="left"
									name="maxShar"
									:rules="[{ required: formData.model === 1, message: '请输入最大分片时长', trigger: 'change' }]"
								>
									<template #label>
										最大分片时长
										<a-tooltip placement="top" title="数值范围:1~60，默认值:30">
											<i class="iconfont icon-information-line"></i>
										</a-tooltip>
									</template>
									<div class="have-unit-box">
										<a-input-number
											v-model:value="formData.maxShar"
											:precision="0"
											:min="1"
											:max="60"
											type="number"
											:style="{ backgroundColor: 'transparent !important', borderColor: 'rgba(240, 246, 252, 0.1) ' }"
											:maxlength="10"
											placeholder="请输入"
										></a-input-number>
										<span class="unit">min</span>
									</div>
								</a-form-item>

								<a-form-item style="padding-bottom: 40px" label-align="left" name="validCycleTime" label="采集时间">
									<global-select-time ref="selectTimeRef" v-model:axis-list="formData.validCycleTime"></global-select-time>
								</a-form-item>
							</a-form>
						</div>
						<div style="margin-top: auto; padding-top: 34px">
							<a-button type="primary" :loading="loading" @click="saveForm">确定</a-button>

							<a-button ghost style="margin-left: 8px" class="btn-default" @click="router.go(-1)">取消</a-button>
						</div>
					</div>
				</div>
			</a-spin>
		</template>
	</conf-module-container>
</template>

<script lang="ts" setup>
import { ConfModuleContainer } from '../../../components/index';
import type { Rule } from 'ant-design-vue/es/form';
import { DataRefluxApi, CameraManagementAPI } from '../../../api';
import { TsSelectOptItem } from '../../../type';
import { g6DeepClone } from 'glasssix-utils-ts';
const route = useRoute();
const router = useRouter();
const loading = ref(false);
const pageLoading = ref(false);
const selectTimeRef = ref<any>(); // 时间段ref
const formRef = ref();
const $message: any = inject('$message');
const formData = reactive({
	status: 1,
	configName: '',
	maxShar: 30,
	alarmTimer: 5,
	model: 0,
	aiSrvTypeList: [],
	deviceIds: [],
	validCycleTime: []
});

const formRules: Record<string, Rule[]> = {
	configName: [{ required: true, message: '请输入配置名称', trigger: 'change' }],
	deviceIds: [{ required: true, message: '请选择回流设备', trigger: 'change' }],
	model: [{ required: true, message: '请选择回流策略', trigger: 'change' }],
	validCycleTime: [{ required: true, message: '请选择采集时间', trigger: 'change' }]
};

const deviceOptions = ref([]);

const deviceInfoList = ref([] as Array<{ id: any; areaOrDeviceId: any; configId: null; name: any }>);
// 递归筛选
const findObjectById = (data: any, id: string): any => {
	for (let i = 0; i < data.length; i++) {
		const obj = data[i];
		if (obj.id === id) {
			return obj;
		}

		if (obj.children && obj.children.length > 0) {
			const result = findObjectById(obj.children, id);
			if (result) {
				return result;
			}
		}
	}
	return null;
};

const AIServiceList = ref<TsSelectOptItem[]>([]);

const getAIServiceList = async (): Promise<void> => {
	let { data } = await CameraManagementAPI.AIServiceList();
	AIServiceList.value = data;
};

const handleKeyPress = (event: { key: string; preventDefault: () => void }) => {
	if (event.key === ' ') {
		event.preventDefault(); // 阻止默认行为
	}
};
// 摄像头
const changeDeviceList = (value: any): void => {
	console.log('选择摄像头', value);

	deviceInfoList.value = [];
	value.forEach((item: any) => {
		const re = findObjectById(deviceOptions.value, item[item.length - 1]);
		console.log(re);

		// 选中盒子时将所有子项的deviceId获取到
		if (re?.children) {
			re.children.forEach((itemChild: any) => {
				if (itemChild.disabled === 0) {
					let itemInfo = {
						id: itemChild.id,
						areaOrDeviceId: itemChild.areaOrDeviceId,
						configId: null,
						name: itemChild.name,
						disabled: itemChild.disabled
					};
					deviceInfoList.value.push(itemInfo);
				}
			});
		} else {
			// 选中子项时直接把deviceId获取到
			let itemInfo = {
				id: re.id,
				areaOrDeviceId: re.areaOrDeviceId,
				configId: null,
				name: re.name
			};
			deviceInfoList.value.push(itemInfo);
		}
	});

	if (deviceInfoList.value.length > 5) {
		$message.error('回流设备不能超过5个');
		changeDeviceList(formData.deviceIds);
		throw new Error('回流设备不能超过5个');
	}
	formData.deviceIds = value;
};

// 删除无效id
const delInvalidId = (treeData: any, deviceId: any): any => {
	const newList = [...new Set(deviceId.flat())];
	let deviceIds = deviceId;
	const getTreeById = (treeData: any, key: any): any => {
		for (let i = 0; i < treeData.length; i++) {
			if (treeData[i].id === key) {
				return false; // 找到了目标节点，返回节点信息
			}
			if (treeData[i].children && treeData[i].children.length > 0) {
				const result = getTreeById(treeData[i].children, key); // 递归查找
				if (!result) {
					return false; // 如果在子节点中找到了目标节点，返回结果
				}
			}
		}

		return key; // 遍历完当前节点和子节点都没有找到目标节点，返回null
	};

	// 删除不存在的id数组
	const delNotIdArry = (): any => {
		newList.forEach((key) => {
			if (getTreeById(treeData, key)) {
				let delKey = getTreeById(treeData, key);
				let del = deviceIds.findIndex((item: any) => item[0] === delKey || item[1] === delKey);
				deviceIds.splice(del, 1);
			}
		});
		return deviceIds;
	};

	return delNotIdArry();
};

const findParentIds = (id: string, data: any[]) => {
	const parentIds: any = [];

	const findParentRecursive = (node: any) => {
		if (node.id === id) {
			parentIds.unshift(node.id); // 将当前节点id添加到数组的开头
			return true;
		}

		if (node.children && node.children.length > 0) {
			for (const child of node.children) {
				if (findParentRecursive(child)) {
					parentIds.unshift(node.id); // 将当前节点id添加到数组的开头
					return true;
				}
			}
		}

		return false;
	};

	for (const tree of data) {
		findParentRecursive(tree);
	}

	return parentIds;
};

const noDisableDevice = (idList: any[], nodes: any[]) => {
	const flattenedIds = Array.from(new Set(idList.flat()));
	nodes.forEach((node) => {
		if (flattenedIds.includes(node.id)) {
			node.disabled = false;
			if (node.children && node.children.length > 0) {
				noDisableDevice(flattenedIds, node.children);
			}
		}
	});
};

const updateParentDisable = (node: { children: any[]; disabled: boolean; type: number }) => {
	if (node.type === 1 && !node.children) {
		node.disabled = true;
		return true;
	}

	if (!node.children || node.children.length === 0) {
		// let isTrue = node.type === 1 ? true : false;
		// node.disabled = isTrue;
		// return isTrue;
		return node.disabled;
	}
	const childDisabledStates = node.children.map((child) => {
		return updateParentDisable(child);
	});

	const allChildrenDisabled = childDisabledStates.every((disabled) => {
		return disabled;
	});

	if (allChildrenDisabled) {
		node.disabled = true;
	}

	return node.disabled;
};

// 详情处理回显已选设备
const detailDeviceIds = ref([]);
const detailDeviceOperation = () => {
	let deviceIds = detailDeviceIds.value;
	// 1、 去掉设备列表没有的id
	deviceIds = !deviceIds ? undefined : delInvalidId(deviceOptions.value, deviceIds);
	// 2、组装回显设备的数据格式 例如：[[1,1-1,1-1-2], [2,2-1,2-1-2]]
	deviceIds.forEach((item: any, index: number, arr: any[]) => {
		arr[index] = findParentIds(item, deviceOptions.value);
	});
	formData['deviceIds'] = deviceIds;
	// 3、回显选择后的设备
	changeDeviceList(formData['deviceIds']);
	// 4、 选择的设备从数据列表里面  将禁用变成可选
	noDisableDevice(formData['deviceIds'], deviceOptions.value);
};

// 获取详情
const getConfigDetail = async () => {
	let res = await DataRefluxApi.configDetail(route.query.id as string);
	if (res.code === 0) {
		let data = res.data;
		Object.keys(formData).forEach((key: number | string) => {
			if (key in data) {
				(formData as any)[key] = data[key];
			}
			if (key === 'deviceIds') {
				let deviceIds = data.device.deviceVos.map((item: any) => item.id);
				detailDeviceIds.value = deviceIds;
			}
		});

		selectTimeRef.value?.setAxisList(formData.validCycleTime);
	}
};

const getVideoDeviceTree = async () => {
	const res: TsRes = await DataRefluxApi.getDeviceTree();
	if (res.code === 0) {
		deviceOptions.value = res.data;
		if (route.query.id) {
			detailDeviceOperation();
		}

		// 找到所有子节点都是disable = true的节点，然后将它们的父节点也设置为disable = true
		res.data.forEach((tree: any) => {
			updateParentDisable(tree);
		});
		deviceOptions.value = res.data;
	}
};

const saveForm = () => {
	formRef.value
		.validate()
		.then(async (result: any) => {
			console.log('保存', result);
			let params = g6DeepClone(formData);
			delete params.deviceIds;
			params.device = {
				deviceVos: deviceInfoList.value,
				deviceNameStr: deviceInfoList.value.map((item: any) => item.name).toString()
			};
			let modifyIdObj = {};
			if (route.query.id) {
				modifyIdObj = {
					id: route.query.id
				};
			}
			const mergeParams = Object.assign({}, modifyIdObj, params);

			if (loading.value) {
				return;
			}
			loading.value = true;
			const res: TsRes = await DataRefluxApi.saveConfig(mergeParams);
			loading.value = false;
			console.log('保存响应', res);
			if (res.code === 0) {
				$message.success('保存成功');
				router.go(-1);
			} else if (res.code === 17) {
				selectTimeRef.value?.setAxisList(formData.validCycleTime, res.data);
			}
		})
		.catch((err: any) => {
			console.log('err', err);
		});
};
//
const changerefluxStrategyOptions = () => {
	formData.aiSrvTypeList = formData.aiSrvTypeList === null ? [] : formData.aiSrvTypeList;
};
onMounted(async () => {
	pageLoading.value = true;
	await getAIServiceList();
	if (route.query.id) {
		await getConfigDetail();
	}
	await getVideoDeviceTree();

	pageLoading.value = false;
});
</script>

<style lang="less" scoped>
.reflux-config-form {
	.form-page {
		--role-header-height: 60px;
		--role-card-height: 400px;

		display: flex;
		overflow-y: auto;
		width: 824px;
		margin: 0 auto;
		padding: 40px 0;
		padding-top: 12px;
		color: @text01;
		flex-direction: column;
		justify-content: center;

		:deep(.ant-form) {
			.ant-form-item-required::after {
				visibility: hidden;
			}
		}

		.title {
			display: inline-block;
			margin-bottom: 16px;

			.text {
				display: inline-block;
				margin-left: 8px;
				font-size: 16px;
				font-weight: 700;
				line-height: 24px;
				color: @text01;
			}
		}

		.form-main {
			display: flex;
			width: 824px;
			border: 1px solid @borderColor02;
			border-radius: 4px;
			padding: 20px 20px 40px;
			background-color: @background02;
			box-shadow: 0 40px 180px 0 rgba(0, 0, 0, 0.35);
			flex-direction: column;

			.form-box {
				.have-unit-box {
					display: flex;
					align-items: center;

					.unit {
						display: inline-block;
						margin-left: 4px;
						color: @text02;
					}
				}
				// 禁用项背景色
				.ant-input-disabled {
					background: @mask02 !important;

					&:focus-visible {
						border: transparent !important;
					}
				}

				.ant-form-item-control-input {
					input {
						height: 36px !important;
					}
				}
			}
		}
	}

	.icon-information-line {
		margin-left: 2px;
		cursor: pointer;
	}
}

:deep(.ant-radio-group) {
	.ant-radio-wrapper {
		border: none !important;
	}
}
</style>
